package executor.impl;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2020-01-08 17:22
 * @notify
 * @version 1.0
 */


import handler.StatementHandler;
import mapping.BoundSql;
import mapping.Configuration;
import mapping.MappedStatement;
import sqlsource.SqlSource;

import javax.sql.DataSource;
import java.sql.*;

public class SimpleExecutor extends BaseExecutor {

    private Configuration configuration;
    private String statementId;
    private Object param;
    private MappedStatement mappedStatement;
    private SqlSource sqlSource;
    private BoundSql boundSql;
    private String sql;
    private Connection connection;
    private StatementHandler statementHandler;
    private Statement statement;

    public SimpleExecutor(Configuration configuration, String statementId, Object param) throws Exception {
        this.configuration = configuration;
        this.statementId = statementId;
        this.param = param;
        execute();
    }

    public Object queryFormDataBase(String statementId, Object param) throws Exception {
        return executeJDBC(param);
    }


    private void execute() throws Exception {
        connection = getConnection();
        mappedStatement = configuration.getMappedStatementById(statementId);
        if (mappedStatement == null) {
            return;
        }
        sqlSource = mappedStatement.getSqlSource();
        boundSql = sqlSource.getBoundSql(param);
        sql = boundSql.getSql();

        statementHandler = configuration.newStatementHandler(mappedStatement.getStatementType());

        statement = statementHandler.prepare(connection, sql);

        statementHandler.setParam(configuration, statement, mappedStatement, param);
    }

    //建立连接
    private Connection getConnection() throws Exception {
        DataSource dataSource = configuration.getDataSource();
        Connection connection = dataSource.getConnection();
        return connection;
    }

    //执行sql
    private Object executeJDBC(Object param) throws Exception {
        Object query = statementHandler.query(configuration, mappedStatement, statement);
        connection.close();
        System.out.println("查询");
        return query;
    }


    @Override
    public boolean insert() throws Exception {
        return statementHandler.insert(statement);
    }
}

